package com.msb.mall.producet.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.msb.common.utils.R;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;

import com.msb.mall.producet.dao.CategoryDao;
import com.msb.mall.producet.entity.CategoryEntity;
import com.msb.mall.producet.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> queryPageWithAll(Map<String, Object> params) {
//        查询所有商品类型
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
//      将商品分类信息拆解为树形结构

        List<CategoryEntity> list = categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(categoryEntity -> {
                    //根据大类找到所有的小类，递归的方式实现
                    categoryEntity.setChildrens(getCategoryChildren(categoryEntity, categoryEntities));
                    return categoryEntity;
                }).sorted((entity1, entity2) -> {
                    return (entity1.getSort() == null ? 0 : entity1.getSort()) - (entity2.getSort() == null ? 0 : entity2.getSort());
                }).collect(Collectors.toList());
//        第一步遍历出所有的大类

//        第二部根据大类找出对应所有的小类
        return list;
    }

    /**
     * 查找该大类下所有的小类，递归查找
     *
     * @param categoryEntity   某个大类
     * @param categoryEntities 所有类别数据
     * @return
     */
    private List<CategoryEntity> getCategoryChildren(CategoryEntity categoryEntity, List<CategoryEntity> categoryEntities) {

        List<CategoryEntity> collect = categoryEntities.stream().filter(entity -> {
            return entity.getParentCid() == categoryEntity.getCatId();
        }).map(entity1 -> {
            entity1.setChildrens(getCategoryChildren(entity1, categoryEntities));
            return entity1;
        }).sorted((entity1, entity2) -> {
            return (entity1.getSort() == null ? 0 : entity1.getSort()) - (entity2.getSort() == null ? 0 : entity2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

}